package com.wframe.project.jnd.services.impl;

import java.util.*;
import javax.servlet.http.HttpSession;

import com.wframe.project.former.entity.ProductsAttrvalBean;
import com.wframe.project.jnd.dao.ProductDao;
import com.wframe.project.jnd.entity.Integral;
import com.wframe.project.jnd.services.IntegralService;
import com.wframe.project.jnd.vo.IntegralRulesVo;
import com.wframe.project.jnd.wx.filter.WechatFilter;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.frame.common.ValidateNumber;
import com.frame.database.JdataBean;
import com.frame.database.util.Seq;
import com.frame.util.EncryptUtil;
import com.wframe.project.former.dataservices.upload.UploadDao;
import com.wframe.project.jnd.dao.UserDao;
import com.wframe.project.jnd.extinterface.sms.SmsUtil;
import com.wframe.project.jnd.rest.util.ClientException;
import com.wframe.project.jnd.rest.util.SessionUser;
import com.wframe.project.jnd.rest.util.WebSession;
import com.wframe.project.jnd.services.UserService;
import com.wframe.project.jnd.util.WebUtils;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserDao userDao;
    @Autowired
    IntegralService integralService;
    private final char[] chars = {'a', 'b', 'c', 'd', 'e', 'f', 't', 'h', 'k', 'm', 's'};

    /**
     * 生成账号编码
     */
    public String createUserCode() {
        String code = new Seq().getKeyId("wbusercodeid").toString();
        Random random = new Random();
        int diff = 9 - code.length();
        for (int i = 0; i < diff; i++) {
            code = chars[random.nextInt(chars.length)] + code;
        }
        return code;
    }

    @Override
    public JdataBean registerByPhone(String phone, String pwd, String smscode, int source) throws Exception {
        if (userDao.getUserByLoginPhone(phone) != null) {
            throw new ClientException("该手机号已被注册", "2");
        }

        SmsUtil sms = new SmsUtil();
        if (!sms.smsCheck(phone, smscode)) {
            throw new ClientException("短信验证码错误", "3");
        }

        sms.removeSmsCode(phone);
        JdataBean user = new JdataBean();

        user.put("phone", phone);
        user.put("loginname", phone);
        user.put("title", phone);
        user.put("loginpwd", EncryptUtil.md5Encode(pwd));
        user.put("loginphone", phone);
        user.put("source", source);

        String uid = userDao.addUser(user);
        //注册送积分
        JdataBean params = new JdataBean();
        params.put("platform", source);
        params.put("type", Integral.Type.REGISTER.ordinal());
        params.put("content", "注册送积分");
        JdataBean rules = integralService.getIntegralRules();
        integralService.updateUserIntegral(uid, rules.getString("integral_register"), params);
        user.remove("loginpwd");
        user.put("userid", WebUtils.aesEncode(uid));

        return user;
    }

    @Override
    public JdataBean registerByAccount(String loginname, String phone, String pwd, String smscode, int source) throws Exception {
        SmsUtil sms = new SmsUtil();
        if (!sms.smsCheck(phone, smscode)) {
            throw new ClientException("短信验证码错误", "3");
        }

        sms.removeSmsCode(phone);
        return registerByAccount(loginname, phone, pwd, source);
    }

    @Override
    public JdataBean registerByAccount(String loginname, String phone, String pwd, int source) throws Exception {
        JdataBean user = new JdataBean();

        user.put("phone", phone);
        user.put("loginname", loginname);
        user.put("title", phone);
        user.put("loginpwd", EncryptUtil.md5Encode(pwd));
        user.put("source", source);

        String uid = userDao.addUser(user);
        //注册送积分
        JdataBean params = new JdataBean();
        params.put("platform", source);
        params.put("type", Integral.Type.REGISTER.ordinal());
        params.put("content", "注册送积分");
        JdataBean rules = integralService.getIntegralRules();
        integralService.updateUserIntegral(uid, rules.getString("integral_register"), params);
        user.remove("loginpwd");
        user.put("userid", WebUtils.aesEncode(uid));

        return user;
    }

    public JdataBean login(String loginname, String pwd, String checkcode, HttpSession session) throws Exception {

        if (loginname.startsWith("jdywtest") && "6889".equals(checkcode)) {
            // 不检查验证码
        } else {
            if (!ValidateNumber.checkAll(checkcode, session)) {
                throw new ClientException("验证码错误", "3");
            }
        }

        String md5pwd = EncryptUtil.md5Encode(pwd);
        JdataBean user = userDao.wblogin(loginname);
        if (user == null) {
            List<JdataBean> userp = userDao.getUserByPhone(loginname);
            if (userp.size() > 0) {
                throw new ClientException("请使用用户名登录", "2");
            } else {
                throw new ClientException("用户名不存在，请重新输入", "2");
            }
        } else if (!StringUtils.trimToEmpty(user.getString("loginpwd")).equalsIgnoreCase(md5pwd)) {
            throw new ClientException("用户名与密码不匹配，请重新输入", "2");
        } else if (user.getInt("state") != 1) {
            throw new ClientException("该账户已经冻结", "4");
        } else {
            JdataBean userCompany = userDao.getUserCompany(user.getString("id"));
            String comname = null;
            if (userCompany != null && (comname = userCompany.getString("name")) != null) {
                user.put("comname", StringUtils.trimToEmpty(comname));
            }
            return loginByUser(user, session);
        }
    }

    @Override
    public JdataBean login(String loginname, String pwd, String checkcode, boolean bindWechat, HttpSession session) throws Exception {
        JdataBean user = login(loginname, pwd, checkcode, session);
        if (bindWechat) {
            WxMpUser wxMpUser = (WxMpUser) session.getAttribute(WechatFilter.WECHAT_USER_KEY);
            if (wxMpUser != null) {
                userDao.bindUserWechat((Integer) user.get("ID"), wxMpUser.getOpenId(), wxMpUser.getUnionId());
            }
        }
        return user;
    }

    /**
     * 退出登陆修改将wechat_openid更新为null
     */
    public void wxLoginOutwe(String wechat_openid, String userid) throws Exception {
        userDao.wxLoginOutwe(wechat_openid, userid);
    }

    @Override
    public JdataBean loginByUser(JdataBean user, HttpSession session) throws Exception {
        if (user != null && session != null) {
            userDao.updateLogintime(user.getString("id"));
            JdataBean bean = new JdataBean();
            bean.put("userid", WebUtils.aesEncode(user.getString("id")));
            bean.put("title", user.getString("nickname"));
            bean.put("comname", user.getString("comname"));
            bean.put("phone", user.getString("phone"));
            if (StringUtils.isBlank(bean.getString("title"))) {
                bean.put("title", user.getString("loginname"));
            }
            SessionUser sessionuser = new SessionUser();
            sessionuser.setUserid(user.getString("id"));
            sessionuser.setUsername(bean.getString("username"));
            sessionuser.setTitle(bean.getString("title"));
            sessionuser.setComname(bean.getString("comname"));
            if (user.getInt("authstate") == 2) sessionuser.setAuth(true);
            WebSession.setWbUser(session, sessionuser);
        }
        return user;
    }

    public JdataBean registerByPhone(String phone, String pwd, String smscode) throws Exception {
        if (userDao.getUserByLoginPhone(phone) != null) throw new ClientException("该手机号已被注册", "2");
        SmsUtil sms = new SmsUtil();
        if (!sms.smsCheck(phone, smscode)) throw new ClientException("短信验证码错误", "3");
        sms.removeSmsCode(phone);
        JdataBean user = new JdataBean();
        user.put("phone", phone);
        user.put("loginname", phone);
        user.put("title", phone);
        user.put("loginpwd", EncryptUtil.md5Encode(pwd));
        user.put("loginphone", phone);
        String uid = userDao.addUser(user);
        user.remove("loginpwd");
        user.put("userid", WebUtils.aesEncode(uid));
        return user;
    }

    public JdataBean registerByAccount(String loginname, String phone, String pwd, String smscode) throws Exception {
        SmsUtil sms = new SmsUtil();
        if (!sms.smsCheck(phone, smscode)) throw new ClientException("短信验证码错误", "3");
        sms.removeSmsCode(phone);
        return registerByAccount(loginname, phone, pwd);
    }

    public JdataBean registerByAccount(String loginname, String phone, String pwd) throws Exception {
        JdataBean user = new JdataBean();
        user.put("phone", phone);
        user.put("loginname", loginname);
        user.put("title", phone);
        user.put("loginpwd", EncryptUtil.md5Encode(pwd));
        String uid = userDao.addUser(user);
        user.remove("loginpwd");
        user.put("userid", WebUtils.aesEncode(uid));
        return user;
    }

    public JdataBean getUser(String id) {
        try{
            integralService.queryUserIntegrals(id);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return userDao.getUser(id);
    }

    public JdataBean getquerywbuser(String id){
        return userDao.getquerywbuser(id);
    }
    public void editUser(JdataBean bean) throws Exception {
        userDao.editUser(bean);
    }

    public void changephone(String oldphone, String newphone, String oldsmscode, String newsmscode, HttpSession session) throws Exception {
        String userid = WebSession.getWbUser(session).getUserid();
        SmsUtil sms = new SmsUtil();
        if (!sms.smsCheck(oldphone, oldsmscode)) throw new ClientException("旧手机短信验证码错误");
        if (!sms.smsCheck(newphone, newsmscode)) throw new ClientException("新手机短信验证码错误");
        JdataBean getu = userDao.getUserByLoginPhone(newphone);
        if (getu != null) throw new ClientException("新手机 号已经被注册");
        sms.removeSmsCode(oldphone);
        sms.removeSmsCode(newphone);
        JdataBean user = new JdataBean();
        user.put("id", userid);
        user.put("loginphone", newphone);
        user.put("phone", newphone);
        userDao.editUser(user);
    }

    public void updatePwd(String oldpwd, String newpwd, HttpSession session) throws Exception {
        String oldpwd_md5 = EncryptUtil.md5Encode(oldpwd);
        String newpwd_md5 = EncryptUtil.md5Encode(newpwd);
        WebSession.checkLogin(session);
        JdataBean user = userDao.getUser(WebSession.getWbUser(session).getUserid());
        if (!user.getString("loginpwd").equals(oldpwd_md5)) throw new ClientException("旧密码不正确");
        JdataBean bean = new JdataBean();
        bean.put("id", user.getString("id"));
        bean.put("loginpwd", newpwd_md5);
        userDao.editUser(bean);
    }

    public JdataBean getUserCompany(String userid) {
        return userDao.getUserCompany(userid);
    }

    @Transactional
    public String saveCompany(JdataBean bean) throws Exception {
        String savetype = bean.getString("savetype");
        String photos = bean.getString("photos");
        bean.remove("photos");
        if ("submit".equals(savetype)) {
            bean.put("state", 1);
            JdataBean user = new JdataBean();
            user.put("id", bean.getString("userid"));
            user.put("authstate", 1);
            userDao.editUser(user);
        }
        bean.put("submittime", new Date());
        bean.remove("savetype");
        String id = userDao.saveCompany(bean);
        userDao.delCompanyQul(id);
        JSONArray arr = JSON.parseArray(photos);
        for (int i = 0; i < arr.size(); i++) {
            JdataBean b = new JdataBean();
            b.put("companyid", id);
            b.put("type", arr.getJSONObject(i).getString("type"));
            b.put("idnum", arr.getJSONObject(i).getString("idnum"));
            b.put("validity_start", arr.getJSONObject(i).getString("start"));
            b.put("validity_end", arr.getJSONObject(i).getString("end"));
            b.put("img", arr.getJSONObject(i).getString("photo"));
            userDao.saveCompanyQul(b);
        }

        return id;
    }

    public List<Map> queryCompanyQul(String comid) {
        return userDao.queryCompanyQul(comid);
    }

    public JdataBean checkloginname(String name) throws ClientException {
        JdataBean user = userDao.getUserByLoginName(name);
        if (user !=null) {
            if (StringUtils.isBlank(user.getString("phone"))  ) {
                throw new ClientException("","4");
            }
        }
        if (user == null) {
            user = userDao.getUserByLoginPhone(name);
            if (user == null) {
                 throw new ClientException("", "2");
            } else return user;
        } else return user;
    }

    public void findpwd(String userid, String phone, String smscode, String newpwd) throws Exception {
        SmsUtil sms = new SmsUtil();
        if (!sms.smsCheck(phone, smscode)) throw new ClientException("短信验证码错误或失效", "3");
        sms.removeSmsCode(phone);
        JdataBean user = new JdataBean();
        user.put("id", userid);
        user.put("loginpwd", EncryptUtil.md5Encode(newpwd));
        userDao.editUser(user);
    }

    public void addBrowse(String userid, int type, int dataid) throws Exception {
        userDao.addBrowse(userid, type, dataid);
    }

    public boolean checkUserAuth(String userid) {
        if (StringUtils.isBlank(userid)) return false;
        JdataBean user = userDao.getUser(userid);
        if (user != null && user.getInt("authstate") == 2) return true;
        else return false;
    }

    public JdataBean statUserPro(String userid, int source) {
        JdataBean stat = new JdataBean();
        stat.put("couponnum", userDao.statUsercoupon(userid, source));
        stat.put("cartnum", userDao.statUsercart(userid));
        return stat;
    }

    public JdataBean getUserByAccount(String account) {
        return userDao.getUserByAccount(account);
    }

    public void writefeedback(JdataBean bean) throws Exception {
        bean.put("writetime", new Date());
        String[] photos = (String[]) bean.get("photoids");
        UploadDao updao = new UploadDao();
        String dataid = updao.createDataid();
        if(photos !=null){
            updao.setPhotoDataIdFeedBack(dataid, photos);//将多图片归属同一组
            bean.put("photodataid", dataid);
            bean.remove("photoids");
        }
        userDao.writefeedback(bean);
    }
    public void PCFeedback(JdataBean bean) throws Exception{
        bean.put("writetime", new Date());
        String[] photos = (String[]) bean.get("photoids");
        UploadDao updao = new UploadDao();
        String dataid = updao.createDataid();
        if(photos !=null){
            updao.setPhotoDataIdFeedBack(dataid, photos);//将多图片归属同一组
            bean.put("photodataid", dataid);
            bean.remove("photoids");
        }
        userDao.PCFeedback(bean);
    }

    @Transactional
    public void saveSignRecord(JdataBean bean){
        bean.put("create_time",new Date());
        try {
            userDao.saveSignRecord(bean);
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
    }
    public JdataBean getquerywbsign(String userid){
        return userDao.getquerywbsign(userid);
    }

//    public void updateIntegral(String userid,int integral) throws Exception{
//        userDao.updateIntegral(userid,integral);
//    }

    public JdataBean queryToday(String userid){
        return userDao.queryToday(userid);
    }


    public JdataBean querysigncount(String userId){
       return userDao.querysigncount(userId);
    }

    @Override
    public void bindPhone(String phone, String smscode, HttpSession session) throws Exception {
        String userid = WebSession.getWbUser(session).getUserid();
        SmsUtil sms = new SmsUtil();
        if (!sms.smsCheck(phone, smscode)) {
            throw new ClientException("手机短信验证码错误");
        }
        sms.removeSmsCode(phone);
        JdataBean user = new JdataBean();
        user.put("id", userid);
        user.put("loginphone", phone);
        user.put("phone", phone);
        userDao.editUser(user);
    }

    @Override
    public JdataBean getUserByWechat(String openid, String unionid) {
        List<JdataBean> wechatUsers = userDao.getUserByWechat(openid, unionid);
        if (wechatUsers != null && wechatUsers.size() == 1) {
            return wechatUsers.get(0);
        }
        return null;
    }
}
